package com.mind.customer.api.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.mind.customer.utils.EnvUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.io.File;

@Component
@Log4j2
public class OSSUtils {
    /**
     * endpoint
     */
    @Value(value = "${oss.endpoint}")
    private String endpoint = "http://oss-cn-chengdu-internal.aliyuncs.com";
    /**
     * bucketName
     */
    @Value(value = "${oss.bucketName}")
    private String bucketName = "n-ali-u-znsh-oss01";

    /**
     * accessKeyId
     */
    @Value(value = "${oss.accessKeyId}")
    private String accessKeyId = "LTAI5t8bQXKaF9E2m9Fd5iEk";

    /**
     * secretAccessKey
     */
    @Value(value = "${oss.secretAccessKey}")
    private String secretAccessKey = "i947SkrkZkLYAw94QQmophseM37qHR";

    @Resource
    private EnvUtils envUtils;

    public void upload(String objectName, String filePath){
        if(!envUtils.getPlatform().equals("tongwei")){
            return;
        }
        DefaultCredentialProvider credentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider(accessKeyId, secretAccessKey);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialProvider);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            log.error("上传oss出现异常：",oe);
        }
    }



    public void download(String objectName, String filePath){
        DefaultCredentialProvider credentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider(accessKeyId, secretAccessKey);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialProvider);
        try {
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(filePath));
        } catch (OSSException oe) {
            log.error("下载oss出现异常：",oe);
        }
    }
}
